const express = require("express");
const db = require("./db.js");
const chalk = require("chalk");

const app = express();
// app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/", async (req, res) => {
  // try {
  //   let back = await db.getDb();

  //   res.send(back.users);
  // } catch (error) {
  //   res.status(500).json({ error });
  // }
  db.getUsers()
    .then((result) => {
      res.send(result);
    })
    .catch((error) => {
      res.status(500).json({ error });
    });
});

app.post("/", async (req, res) => {
  const body = req.body;
  if (!body) {
    return res.status(403).json({
      error: "缺少用户信息",
    });
  }
  // const jsonObj = await db.getDb();
  // body.id = jsonObj.users[jsonObj.users.length - 1].id + 1;
  // jsonObj.users.push(body);
  // try {
  // let w = await db.serveDb(jsonObj);
  // if (!w) {
  //   res.status(200).send({
  //     msg: "添加成功",
  //   });
  // }
  // } catch (error) {
  //   res.status(500).json({
  //     error,
  //   });
  // }
  db.addUser(body)
    .then((result) => {
      res.status(200).send({
        msg: "添加成功",
      });
    })
    .catch((error) => {
      console.log(error);
      res.status(500).json({
        error,
      });
    });
});

app.put("/:id", async (req, res) => {
  try {
    let userInfo = await db.getDb();
    let userId = Number.parseInt(req.params.id);
    let user = userInfo.users.find((item) => item.id === userId);
    if (!user) {
      res.status(403).json({
        error: "用户不存在",
      });
    }
    const body = req.body;
    user.username = body.username ? body.username : user.username;
    user.age = body.age ? body.age : user.age;
    userInfo.users[userId - 1] = user;
    if (!(await db.serveDb(userInfo))) {
      res.status(201).json({
        msg: "修改成功",
      });
    }
  } catch (error) {
    res.status(500).json({
      error,
    });
  }
});

app.listen(3100, () => {
  console.log("Server is running on ", chalk.green("http://localhost:3100"));
});

app.on("close", () => {
  db.closeDb();
  console.log("Server closed");
});
